package com.battcn.demo4;

import java.util.List;

/**
 * @author Levin
 * @date 2017-12-06.
 */
public class ThreadLifeCycleListener implements LifeCycleListener {

    private static final Object LOCK = new Object();

    public void concurrentQuery(List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            return;
        }
        ids.forEach(id ->
                new Thread(new ObservableRunnable(this) {
                    @Override
                    public void run() {
                        try {
                            notifyChange(new RunnableEvent(RunnableState.RUNNING, Thread.currentThread(), null));
                            System.out.printf("根据 [%s] 查询 \n", id);
                            Thread.sleep(5000L);
                            if (id.equals("T3")) {
                                // 故意模拟报错
                                int i = 10 / 0;
                            }
                            notifyChange(new RunnableEvent(RunnableState.DOWN, Thread.currentThread(), null));
                        } catch (Exception e) {
                            notifyChange(new RunnableEvent(RunnableState.ERROR, Thread.currentThread(), e));
                        }
                    }
                }).start()
        );

    }

    @Override
    public void onEvent(ObservableRunnable.RunnableEvent event) {
        synchronized (LOCK) {
            System.out.println("The Runnable [" + event.getThread().getName() + "] data changed and state is " + event.getState().name());
            if (event.getCause() != null) {
                System.out.println("The Runnable [" + event.getThread().getName() + "] process failed and state is " + event.getState().name());
                event.getCause().printStackTrace();
            }
        }
    }
}
